package com.buddy.sds.common.mybatis;

import com.buddy.sds.common.ContextHolder;
import org.apache.ibatis.cache.Cache;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RedisCache implements Cache {

    private String id;

    private static final String prefix = "MYBATIS_";

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private RedisTemplate<Object,Object> redisTemplate;

    public RedisCache(String id){

        this.id = id;


    }

    private boolean checkRedis(){

        if(redisTemplate == null){
            ApplicationContext context = ContextHolder.getApplicationContext();

            redisTemplate = (RedisTemplate<Object, Object>) context.getBean("redisTemplate");
        }

        return redisTemplate != null;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void putObject(Object key, Object value) {
        if(checkRedis())
            redisTemplate.opsForValue().set( prefix + key,value);
    }

    @Override
    public Object getObject(Object key) {
        if(checkRedis())
        return redisTemplate.opsForValue().get(prefix + key);

        return null;
    }

    @Override
    public Object removeObject(Object key) {
        if(checkRedis())
            return redisTemplate.delete(prefix + key);
        else
            return null;
    }

    @Override
    public void clear() {

        if(checkRedis())
            redisTemplate.delete(prefix + "*");
    }

    @Override
    public int getSize() {
        if(checkRedis())
            return  redisTemplate.opsForValue().size(prefix + "*").intValue();

        return 0;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }
}
